<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        width="60%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <div class="unit-form-container">
                        <!-- 基本单位 -->
                        <div class="form-row">
                            <el-form-item :label="t('基本单位')" prop="baseUnit">
                                <el-input v-model="state.baseUnit" :placeholder="t('基本单位应为最小度量单位')"></el-input>
                            </el-form-item>
                            <div class="form-text">{{ t('基本单位应为最小度量单位') }}</div>
                        </div>

                        <!-- 副单位列表 -->
                        <div v-for="(unit, index) in state.subUnits" :key="index" class="form-row sub-unit-row">
                            <div class="sub-unit-label">
                                <el-button type="primary" size="small" circle @click="addSubUnit">
                                    <Icon name="el-icon-Plus" />
                                </el-button>
                                <el-button type="danger" size="small" circle @click="removeSubUnit(index)" :disabled="index === 0 && state.subUnits.length === 1">
                                    <Icon name="el-icon-Delete" />
                                </el-button>
                                <span>{{ t('副单位') + (index + 1) }}</span>
                            </div>
                            <div class="sub-unit-content">
                                <el-input v-model="unit.name" :placeholder="t('请输入单位名称')"></el-input>
                                <span class="equal-sign">=</span>
                                <el-input v-model="unit.rate" type="number" :placeholder="t('请输入换算进率')"></el-input>
                            </div>
                        </div>
                    </div>

                    <FormItem :label="t('yxerp.unit.conversion.code')" type="string" v-model="baTable.form.items!.code" prop="code" :placeholder="t('Please input field', { field: t('yxerp.unit.conversion.code') })" />
                    <FormItem :label="t('yxerp.unit.conversion.status')" type="radio" v-model="baTable.form.items!.status" prop="status" :input-attr="{ content: { '0': t('yxerp.unit.conversion.status 0'), '1': t('yxerp.unit.conversion.status 1') } }" :placeholder="t('Please select field', { field: t('yxerp.unit.conversion.status') })" />
                    <FormItem :label="t('yxerp.unit.conversion.weigh')" type="number" v-model="baTable.form.items!.weigh" prop="weigh" :input-attr="{ step: 1 }" :placeholder="t('Please input field', { field: t('yxerp.unit.conversion.weigh') })" />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="handleSubmit" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { inject, reactive, ref, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'
import Icon from '/@/components/icon/index.vue'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

interface SubUnit {
    name: string;
    rate: string | number;
}

const state = reactive({
    baseUnit: '',
    subUnits: [{ name: '', rate: '' }] as SubUnit[],
})

// 添加副单位行
const addSubUnit = () => {
    state.subUnits.push({ name: '', rate: '' });
}

// 删除副单位行
const removeSubUnit = (index: number) => {
    if (state.subUnits.length > 1) {
        state.subUnits.splice(index, 1);
    }
}

// 当表单初始化或数据变化时，解析数据到组件状态
const parseFormData = () => {
    if (!baTable.form.items) return;

    // 解析 name 字段（单位名称）
    if (baTable.form.items.name) {
        const names = baTable.form.items.name.split(',');
        if (names.length > 0) {
            state.baseUnit = names[0];
            
            // 解析副单位
            state.subUnits = [];
            for (let i = 1; i < names.length; i++) {
                state.subUnits.push({
                    name: names[i],
                    rate: '' // 初始化为空，下面从conversion中填充
                });
            }
        }
    }

    // 解析 conversion 字段（换算率）
    if (baTable.form.items.conversion) {
        const rates = baTable.form.items.conversion.split(':');
        if (rates.length > 0) {
            // 第一个应该是1，是基准单位
            for (let i = 1; i < rates.length && i - 1 < state.subUnits.length; i++) {
                state.subUnits[i - 1].rate = rates[i];
            }
        }
    }

    // 如果没有副单位，至少添加一个空白行
    if (state.subUnits.length === 0) {
        state.subUnits.push({ name: '', rate: '' });
    }
}

// 处理表单提交
const handleSubmit = async () => {
    if (!formRef.value) return;
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            // 构建单位名称字符串
            const names = [state.baseUnit];
            state.subUnits.forEach(unit => {
                if (unit.name) {
                    names.push(unit.name);
                }
            });
            
            // 构建换算率字符串
            const rates = ['1']; // 基准单位换算率固定为1
            state.subUnits.forEach(unit => {
                if (unit.rate) {
                    rates.push(unit.rate.toString());
                }
            });
            
            // 将处理后的数据设置回表单
            baTable.form.items!.name = names.join(',');
            baTable.form.items!.conversion = rates.join(':');
            
            // 调用原有的提交方法
            baTable.onSubmit(formRef.value);
        }
    });
}

// 监听表单操作和数据变化
watch(() => baTable.form.operate, () => {
    if (['Add', 'Edit'].includes(baTable.form.operate || '')) {
        setTimeout(() => {
            parseFormData();
        }, 100);
    }
});

watch(() => baTable.form.items, () => {
    if (['Add', 'Edit'].includes(baTable.form.operate || '')) {
        parseFormData();
    }
}, { deep: true });

onMounted(() => {
    if (['Add', 'Edit'].includes(baTable.form.operate || '')) {
        parseFormData();
    }
});

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    //baseUnit: [buildValidatorData({ name: 'required', title: t('基本单位') })],
    code: [buildValidatorData({ name: 'required', title: t('yxerp.unit.conversion.code') })],
    create_time: [buildValidatorData({ name: 'date', title: t('yxerp.unit.conversion.create_time') })],
    update_time: [buildValidatorData({ name: 'date', title: t('yxerp.unit.conversion.update_time') })],
})
</script>

<style scoped lang="scss">
.unit-form-container {
    margin-bottom: 20px;
    
    .form-row {
        margin-bottom: 15px;
    }
    
    .form-text {
        margin-left: 160px;
        color: #909399;
        font-size: 12px;
        margin-top: 5px;
    }
    
    .sub-unit-row {
        display: flex;
        flex-direction: column;
        margin-bottom: 20px;
        margin-left: 160px;
        border: 1px dashed #dcdfe6;
        padding: 15px;
        border-radius: 4px;
    }
    
    .sub-unit-label {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        
        span {
            margin-left: 10px;
            font-weight: bold;
        }
        
        .el-button {
            margin-right: 5px;
        }
    }
    
    .sub-unit-content {
        display: flex;
        align-items: center;
        
        .el-input {
            width: 45%;
        }
        
        .equal-sign {
            margin: 0 15px;
            font-weight: bold;
        }
    }
}
</style>
